﻿using AutoMapper;
using B.S.DataBase.MyProject.ErrorCode;
using D.Traceability.Domain;
using D.Traceability.Infrastructure.Infrastructure;
using D.Traceability.Write.API.APPlicant.Command.DeepCommand;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.Traceability.Write.API.APPlicant.CommandHandler.DeepCommandHandler
{
    /// <summary>
    /// 添加/修改深加工信息-命令
    /// </summary>
    public class AddUpdateDeepCommandHandler : IRequestHandler<AddUpdateDeepCommand, APIResult<string>>
    {
        private readonly IBaseRepository<SU_DeepModel> baseRepository;
        private readonly IMapper mapper;

        public AddUpdateDeepCommandHandler(IBaseRepository<SU_DeepModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }
        //////////////////////深加工信息////////////////////////////
        /// <summary>
        /// 添加/修改深加工信息-命令
        /// </summary>
        public async Task<APIResult<string>> Handle(AddUpdateDeepCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();

            //////////////////////深加工业信息////////////////////////////
            //查询是否含有数据(通过 生产批次 TraceaBatch查询)
            var obj = await baseRepository.GetAll().Result.FirstOrDefaultAsync(x => x.TraceaBatch == request.TraceaBatch && x.TraceaIsDelete == false);
            //////////////////////深加工业信息////////////////////////////
            //有数据执行修改操作
            if (obj != null)
            {
                obj.DeepLeaderName = request.DeepLeaderName;                        //班组
                obj.DeppChargeName = request.DeppChargeName;            //负责人
                int res = await baseRepository.Update(obj);
                if (res > 0)
                {
                    result.Code = APIEnum.设置成功;
                    result.Msg = APIEnum.设置成功.ToString();
                    result.data = res.ToString();
                }
                else
                {
                    result.Code = APIEnum.设置失败;
                    result.Msg = APIEnum.设置失败.ToString();
                    result.data = res.ToString();
                }
            }
            else
            {
                //添加操作
                var model = mapper.Map<SU_DeepModel>(request);
                int res = await baseRepository.Add(model);
                if (res > 0)
                {
                    result.Code = APIEnum.设置成功;
                    result.Msg = APIEnum.设置成功.ToString();
                    result.data = res.ToString();
                }
                else
                {
                    result.Code = APIEnum.设置失败;
                    result.Msg = APIEnum.设置失败.ToString();
                    result.data = res.ToString();
                }
            }
            return await Task.FromResult(result);
        }
    }
}
